package com.weishenai.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.weishenai.Entity.Token;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: weishenai
 * @Date: 2021/10/05/22:53
 * @Description:
 */
public class TokenUtil {
    //过期时间设置(30分钟)
    private static final long EXPIRE_TIME = 30 * 60 * 1000;

    //私钥设置(随便乱写的)
    private static final String TOKEN_SECRET = "weiShenAi_token_secret";

    public String getToken(Token token) {

        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        //加密算法设置
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

        //头部信息
        Map<String, Object> header = new HashMap<>(2);
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        //返回token字符串
        return JWT.create()
                .withHeader(header)
                .withClaim("username", token.getUserName())
                .withClaim("lastLogin", token.getLastLogin())
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public Token getTokenData(String token) {
        DecodedJWT jwt = JWT.decode(token);
        Token tk = new Token();

        tk.setUserName(jwt.getClaim("username").asString());
        tk.setLastLogin(jwt.getClaim("lastLogin").asDate());

        return tk;
    }

    public String creatToken(String role) {
        //这里是传入的是token对象，决定token的内容
        Token tk = new Token();
        //获取时间用
        Date date = new Date();

        tk.setUserName(role);
        tk.setLastLogin(date);
        //交给上面的实现类得到token
        return getToken(tk);
    }

//    校验token
    public boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }

    }

}
